<template>
  <div class="custom-pagetable">
    <Table
      class="custom-table"
      :columns="columns"
      :data="tableData"
      :stripe="stripe"
      :border="border"
      :show-header="showHeader"
      :width="width"
      :height="height"
      :highlight-row="highlightRow"
      :max-height="maxHeight"
      :loading="loading"
      :disabled-hover="disabledHover"
      :row-class-name="rowClassName"
      :size="size"
      :no-data-text="noDataText"
      :no-filtered-data-text="noFilteredDataText"
      :span-method="spanMethod"
      @on-current-change="onCurrentChange"
      @on-select="onSelect"
      @on-select-cancel="onSelectCancel"
      @on-select-all="onSelectAll"
      @on-select-all-cancel="onSelectAllCancel"
      @on-selection-change="onSelectionChange"
      @on-sort-change="onSortChange"
      @on-filter-change="onFilterChange"
      @on-row-click="onRowClick"
      @on-row-dbclick="onRowDbclick"
      @on-expand="onExpand"
      @on-cell-click="onCellClick">
      <slot name="header" />
      <slot name="footer" />
      <slot name="loading" />
    </Table>

    <div v-if="isPages && tableData.length > 0" class="page">
      <CustomPage
        :size="pageBoxSize"
        :page-size-opts="pageSizeOpts"
        :current="current"
        :total="total"
        :page-size="curPageSize"
        :showElevator="showElevator"
        :showSizer="showSizer"
        :show-total="showTotal"
        @on-change="changePage"
        @on-page-size-change="changeSize"
      ></CustomPage>
    </div>
  </div>
</template>
<script>
import { mapActions } from 'vuex'
import { HttpUrl } from 'api/config'
import { ajaxPostFormData } from 'api/axios'
import { removeObjUndefined } from 'common/js/utils'

export default {
  emits: ['handleData', 'on-current-change', 'on-select', 'on-select-cancel', 'on-select-all', 'on-select-all-cancel', 'on-selection-change', 'on-sort-change', 'on-filter-change', 'on-row-click', 'on-expand', 'on-cell-click', 'on-change'],
  props: {
    columns: {
      type: Array,
      default: () => []
    },
    stripe: {
      type: Boolean,
      default: false
    },
    border: {
      type: Boolean,
      default: false
    },
    showHeader: {
      type: Boolean,
      default: true
    },
    width: {
      type: [Number, String],
      default: '100%'
    },
    height: {
      type: [Number, String]
    },
    maxHeight: {
      type: [Number, String]
    },
    disabledHover: {
      type: Boolean,
      default: false
    },
    highlightRow: {
      type: Boolean,
      default: false
    },
    rowClassName: {
      type: Function,
      default: () => {
        return ''
      }
    },
    size: {
      type: String
    },
    noDataText: {
      type: String
    },
    noFilteredDataText: {
      type: String
    },
    spanMethod: {
      type: Function
    },
    isPages: {
      type: Boolean,
      default: true
    },
    // 跨页记录当前勾选
    isSelectSpread: {
      type: Boolean,
      default: false
    },
    pageSizeOpts: {
      type: Array,
      default: () => [10, 20, 50]
    },
    pageSize: {
      type: Number,
      default: 10
    },
    pageBoxSize: {
      type: String,
      default: 'small'
    },
    showSizer: {
      type: Boolean,
      default: true
    },
    showElevator: {
      type: Boolean,
      default: true
    },
    showTotal: {
      type: Boolean,
      default: true
    },
    listUrl: {
      type: String,
      default: ''
    },
    searchValue: {
      type: Object,
      default: () => ({ })
    },
    // 渲染表格自动请求数据
    isAutoLoad: {
      type: Boolean,
      default: true
    },
    isCustomUrl: {
      type: Boolean,
      default: false
    },
    defaultHighlightValKey: {
      type: String,
      default: 'id'
    },
    defaultHighlight: {},
    filterDataFn: {
      type: Function
    },
    axiosIsFormData: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      current: 1,
      total: 0,
      curPageSize: this.pageSize,
      loading: false,
      tableData: [],
      // 已选择的数据
      selectedData: [],
      // 当前页的数据
      curPageData: []
    }
  },
  mounted () {
    this.init()
  },
  methods: {
    // 初始化
    init () {
      // 如是开启渲染表格后自动加载数据
      if (this.isAutoLoad) {
        this.handleTable()
      }
    },
    // 渲染表格
    handleTable (page) {
      if (this.isCustomUrl) {
        this._getCustomData(page)
      } else {
        this._getList(page)
      }
    },
    onCurrentChange (currentRow, oldCurrentRow) {
      this.$emit('on-current-change', currentRow, oldCurrentRow)
    },
    // 选中时
    onSelect (selection, row) {
      this.$emit('on-select', selection, row)
    },
    // 取消时
    onSelectCancel (selection, row) {
      this.$emit('on-select-cancel', selection, row)
    },
    onSelectAll (selection) {
      this.$emit('on-select-all', selection)
    },
    onSelectAllCancel (selection) {
      this.$emit('on-select-all-cancel', selection)
    },
    onSelectionChange (selection) {
      this.selectedData = selection

      this.$emit('on-selection-change', selection)
    },
    onSortChange (column, key, order, desc) {
      this.$emit('on-sort-change', column, key, order, desc)
    },
    onFilterChange () {
      this.$emit('on-filter-change')
    },
    onRowClick (row, index) {
      this.$emit('on-row-click', row, index)
    },
    onRowDbclick (row, index) {
      this.$emit('on-row-click', row, index)
    },
    onExpand (row, status) {
      this.$emit('on-expand', row, status)
    },
    onCellClick (row, column) {
      this.$emit('on-cell-click', row, column)
    },
    changePage (page) {
      this.current = page
      this.handleTable(page)
      this.$emit('on-change', page)
    },
    changeSize (size) {
      this.curPageSize = size
      this.handleTable()
    },
    // 给已选中的行添加标记
    tagSelectedData () {
      if (this.selectedData.length > 0 && this.tableData.length > 0) {
        this.tableData.forEach((tbItem) => {
          this.selectedData.forEach((selItem) => {
            if (tbItem.id === selItem.id) {
              this.$set(tbItem, '_checked', true)
            }
          })
        })
      }
    },
    handleHighlightData () {
      this.tableData.forEach((item) => {
        if (item[this.defaultHighlightValKey] === this.defaultHighlight) {
          this.$set(item, '_highlight', true)
          this.onCurrentChange(item, {})
        }
      })
    },
    getSelectData () {
      return JSON.parse(JSON.stringify(this.selectedData))
    },
    getTableData () {
      return JSON.parse(JSON.stringify(this.tableData))
    },
    clearTableData () {
      this.tableData = []
      this.current = 1
      this.total = 0
      this.tableData = []
      this.selectedData = []
    },
    showLoading () {
      this.loading = true
    },
    hideLoading () {
      this.loading = false
    },
    // 默认地址后缀获取表格
    async _getList (page = 1) {
      let params = {
        ...removeObjUndefined({
          data: this.searchValue
        }),
        pageNum: page,
        pageSize: this.curPageSize,
      }

      this.loading = true

      let res = null

      if (this.axiosIsFormData) {
        const url = `${HttpUrl}${this.listUrl}`

        res = await ajaxPostFormData(url, {
          pageNum: page,
          pageSize: this.curPageSize,
          ...params
        })
      } else {
        let url = this.listUrl

        if (this.isPages) {
          url += `?pageNum=${page}&pageSize=${this.curPageSize}`
        }

        res = await this.GET_VIEW({
          module: url,
          ...params
        })
      }

      if (res) {
        this.loading = false
        this.current = page

        if (this.filterDataFn) {
          const tableFilterData = this.filterDataFn(res)

          this.total = tableFilterData.total
          this.tableData = tableFilterData.tableData
        } else {
          this.total = res.count
          this.tableData = res.list
        }
        // 如果开启了跨页勾选，每次获取表格数据时 匹配已选中添加_checked标记
        this.isSelectSpread && this.tagSelectedData()
        // 处理默认高亮行
        this.highlightRow && this.defaultHighlight && this.handleHighlightData()
        this.selectedData = []
        // 外面做其他处理
        this.$emit('handleData', res)
      } else {
        this.loading = false
        const obj = []
        
        if (this.filterDataFn) {
          this.tableData = this.filterDataFn(obj)
        } else {
          this.tableData = obj
        }
        // this.tableData = []
      }
    },
    // 自定义地址获取表格
    async _getCustomData (page = 1) {
      let params = {
        pageNo: page,
        pageSize: this.curPageSize,
        ...removeObjUndefined({
          data: this.searchValue
        })
      }

      this.loading = true

      const res = await this.GET_DATA({
        dataUrl: this.listUrl,
        ...params
      })

      if (res) {
        this.loading = false
        this.current = res.page
        this.total = res.total
        this.tableData = res.data
        // 如果开启了跨页勾选，每次获取表格数据时 匹配已选中添加_checked标记
        this.isSelectSpread && this.tagSelectedData()
        // 处理默认高亮行
        this.highlightRow && this.defaultHighlight && this.handleHighlightData()
        // 外面做其他处理
        this.$emit('handleData', res)
      } else {
        this.loading = false
        this.tableData = []
      }
    },
    ...mapActions({
      GET_VIEW: 'GET_VIEW',
      GET_DATA: 'GET_DATA'
    })
  }
}
</script>
<style lang="scss">
.custom-pagetable {
  .ivu-table-cell {
    padding-left: 5px !important;
    padding-right: 5px !important;
  }
  > .page {
    padding: 15px;
  }
}
</style>
